/**
 * 
 */
package com.wubo.sec.web.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.wubo.common.util.CollectionUtils;
import com.wubo.common.util.StringUtils;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.UserData;
import com.wubo.sec.filter.AuthorityBeforeFilter;
import com.wubo.sec.model.Authority;
import com.wubo.sec.service.IAuthorityService;

import flexjson.JSONSerializer;

/**
 * @author wubo
 * @CreateDate 2010-8-6
 * @version 1.0.01
 */
@Controller
public class AuthMgtAction extends BaseSecAction {

	@Autowired
	private IAuthorityService authorityService;

	public IAuthorityService getAuthorityService() {
		return authorityService;
	}

	public void setAuthorityService(IAuthorityService authorityService) {
		this.authorityService = authorityService;
	}

	private List<Authority> auths;
	
	private Authority auth;
	
	private String id;
	
	private String authName;
	
	private String orderby;
	
	private String locked;
	
	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getLocked() {
		return locked;
	}

	public void setLocked(String locked) {
		this.locked = locked;
	}

	public List<Authority> getAuths() {
		return auths;
	}

	public void setAuths(List<Authority> auths) {
		this.auths = auths;
	}
	
	public Authority getAuth() {
		return auth;
	}

	public void setAuth(Authority auth) {
		this.auth = auth;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getAuthName() {
		return authName;
	}

	public void setAuthName(String authName) {
		this.authName = authName;
	}

	public String getOrderby() {
		return orderby;
	}

	public void setOrderby(String orderby) {
		this.orderby = orderby;
	}

	public String list(){
		String where = " where 1=1";
		if(StringUtils.hasText(authName)){
			where = " where a.name like '%"+authName+"%'";
		}
		//按类别查询
		if(StringUtils.hasText(type)){
			where += " and type like '%"+type+"%'";
		}
		
		//按锁定状态查询
		if(!StringUtils.isEmpty(locked)){
			if(!(locked.trim().equals("2")))
			{
				where += " and locked="+locked;
			}
		}
		if(StringUtils.isEmpty(orderby)){
			orderby = " order by name";
		}
		
		where += new AuthorityBeforeFilter().sift();
		
		total = authorityService.getTotal(where);
		
		where += orderby;
		
		auths = authorityService.getSplitPage(start, limit, where);
		
		/*UserData user = SecurityManager.getCurrentUser();
		if(! (user instanceof User) ){
			throw new SecurityException("Only Backend User can access this method !");
		}
		Set<Authority> userAuths = user.getAllAuthorities();
		if(userAuths != null){
			userAuths.addAll(auths);
			
			auths = new ArrayList<Authority>(userAuths);
			auths = CollectionUtils.uniqueList(auths);
		}*/

		//处理排序和过滤
		/*List<Authority> temp = new ArrayList<Authority>();
		if(StringUtils.hasText(authName)){
			for(int i=0; i<auths.size(); i++){
				if(auths.get(i).getName().indexOf(authName) != -1){
					temp.add(auths.get(i));
				}
			}
		}else{
			temp.addAll(auths);
		}

		auths = new ArrayList<Authority>(temp);

		if(!StringUtils.hasText(orderby)){
			orderby = "code";
		}
		if("code".equals(orderby)){
			Collections.sort(auths);
		}else{
			Collections.sort(auths, new Comparator<Authority>() {
				public int compare(Authority o1, Authority o2) {
					return o1.getName().compareTo(o2.getName());
				};
			});
		}*/
		
		setUserAttributesToRequest();
		
		return SUCCESS;
	}
	/**
	 * 为权限分配服务
	 * @return
	 */
	public String listForAssign(){
		String where = "where 1=1";
		if(StringUtils.hasText(authName)){ //过滤权限名
			where = "where a.code like '%"+authName+"%' or a.name like '%"+authName+"%'";
		}
		UserData user = SecurityManager.getCurrentUser();
		
		if(SecurityManager.isAdmin() || SecurityManager.hasAdminAuth(user)){
			auths = authorityService.find(where+" order by a.type, a.code", null);
		} else {
			
			auths = new ArrayList<Authority>(user.getAllAuthorities());
			
			if(! SecurityManager.isMarkLocked()){
				auths.addAll( authorityService.findRunAs(where+new AuthorityBeforeFilter().sift(), null) );
				auths = CollectionUtils.uniqueList(auths);
			}
			if(StringUtils.hasText(authName)){ //过滤权限名
				List<Authority> temp = auths;
				auths = new ArrayList<Authority>();
				for(Authority auth: temp){
					if(auth.getCode().indexOf(authName) == -1 || auth.getName().indexOf(authName) == -1){
						continue;
					}
					auths.add(auth);
				}
			}
			java.util.Collections.sort(auths);
		}
		String result = ServletActionContext.getRequest().getParameter("result");
		if(StringUtils.hasText(result)){
			return result;
		}
		return "checkbox";
	}

	private String q; //用于AutoComplete
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	public void autoComplete() {
		try{
			List<String[]> names = authorityService.listName(q);
			json(new JSONSerializer().serialize(names));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
	}
	
	public void autoCompleteType() {
		try{
			List<String[]> types = authorityService.listType(q);
			//去除重复项
			HashSet<String[]> h = new HashSet<String[]>(types);
			types.clear();
			types.addAll(h);
			json(new JSONSerializer().serialize(types));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
	}
	
	public String edit(){
		try{
			authorityService.update(auth);
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
	
	public String add(){
		try{
			authorityService.create(auth);
			
			jsonSuccess(null);
			
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
	
	
	public String del(){
		authorityService.delete(authorityService.get(id));
		flag = true;
		
		list();
		
		return SUCCESS;
	}
	
}
